package com.type.web;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.annotation.Resource;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpSession;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.type.service.TypeTenService;
import com.type.vo.MailVO;

/**
 * 메일 매니저 컨트롤러 (타입 10)
 * @author daou-ljhjoin
 *
 */
@Controller
public class TypeTenController {
	@Resource(name ="TypeTenService")
	private TypeTenService service;

	/**
	 * 메일 쓰기 폼 열기
	 * @return url
	 */
	@RequestMapping("openMailWrite.do")
	public String openMailWrite(){
		return "/type/typeTen/writeMail";
	}
	
	@RequestMapping("sendMail.do")
	public String sendMail(@ModelAttribute("mailVO")MailVO mail, @RequestParam("address") String address,
			@RequestParam(value="addressCC", required=false) String addressCC, Model model, HttpSession session){
		Properties props = new Properties();
		props.put("mail.smtp.host","localhost");		//host : localhost (아파치 james run 후에 실행)
		props.put("mail.smtp.port","25");				//port : 25 (기본,생략가능)
		props.put("mail.smtp.username","system");		//user
		props.put("mail.smtp.password","system");		//password
		Session sessionMail = Session.getDefaultInstance(props, null);		//세팅한 property를 session 에 주입
	
		String[] receive = 	address.split(",");	
		String[] carbonCopy =null;
		if(addressCC != null){
			carbonCopy=addressCC.split(",");
		}
		
		try{
			MimeMessage message = new MimeMessage(sessionMail); 			//세팅한 sessionMail을 message에 주입
			MimeMessageHelper helper = new MimeMessageHelper(message,true, "utf-8");
			
			helper.setFrom(new InternetAddress(mail.getSender()));	//보내는 사람
			for(int i=0; i<receive.length; i++){		// 수신자들
				helper.addTo(receive[i]);
			}
			if(addressCC!=null){
				for(int i=0; i<carbonCopy.length; i++){		//참조자들
					helper.addCc(carbonCopy[i]);
				}
			}
			helper.setSubject(mail.getTitle());		//제목
			helper.setText(mail.getContent());		//내용
			
			service.insertSendMailInfo(mail,address,addressCC);		//DB에 저장하기 위해 (mailVO, address, cc 가공)
			
			String fileUrl = mail.getUpfile().getOriginalFilename(); 		//첨부파일 처리
			if(mail.getAttachedFile()==null || mail.getAttachedFile().equals(null) ){
			}else{
				FileSystemResource file = new FileSystemResource("c:/" +fileUrl);
				helper.addAttachment(mail.getUpfile().getOriginalFilename(),file );
			}
			Transport.send(message);				// 세팅한 message를 보낸다.
			
			int count=receive.length;			//보낸사람(수신) 카운트
			if(addressCC !=null){
				count += carbonCopy.length;		//보낸사람(참조) 카운트
			}
			model.addAttribute("message","메일을 성공적으로 전송했습니다." );
			model.addAttribute("sender",mail.getSender()+ "님께서 " );
			model.addAttribute("count","총 "+count + "명에게 전송");
			
		} catch(MessagingException me){
			me.printStackTrace();
			System.out.println(me.getMessage());
			model.addAttribute("message", me.getMessage()+ "<br>: 메일 전송 실패");
		}catch(Exception e){
			e.printStackTrace();
			System.out.println(e.getMessage());
			model.addAttribute("message", e.getMessage()+ "<br>: 메일전송 실패");
		}
		return "type/typeTen/transfer";
	}
	
	/**
	 * 메일 읽기 폼 열기
	 * @return url
	 * @throws MessagingException 
	 */
	@RequestMapping("openMailForRead.do")
	public String openMailForRead(Model model) throws MessagingException{
		Properties props = new Properties();
		Session sessionMail = Session.getDefaultInstance(props, null);		//세팅한 property를 session 에 주입
		Store store =null;
		Folder folder =null;
		try {
			store = sessionMail.getStore("pop3");		//받은 메일 확인 하기 위해 pop3를 이용한다.
			store.connect("localhost", "system", "system");
			
			folder = store.getFolder("INBOX");
			folder.open(Folder.READ_ONLY);
			
			Message message[] = folder.getMessages();
			
			for(int i=0; i<message.length; i++){
				System.out.println((i+1) + "번째 메일 ");
				System.out.println("보낸사람:" + message[i].getFrom()[0] );
				System.out.println("메일제목 : " + message[i].getSubject());
				System.out.println("내용의클래스파일 : "+message[i].getContent().getClass());
				System.out.println(" " + message[i].getDescription());
				String content = "";
				Address[] address = message[i].getAllRecipients();
				String to = "";
				for(int j=0; j<address.length; j++){
					to = address[j].toString() + ", ";
				}
				if(message[i].getContent() instanceof String){
					content = (String) message[i].getContent();
				} else if(message[i].getContent() instanceof MimeMultipart){
						MimeMultipart contents = (MimeMultipart) message[i].getContent();
						InputStream is =null;
						for(int j=0; j<contents.getCount();j++){
							//System.out.println(contents.getBodyPart(j)+"바디.내용타입 :"+contents.getBodyPart(j).getContentType());	//text/html, text/plain, multipart/*
							//System.out.println(contents.getBodyPart(j)+"바디.포지션 :"+contents.getBodyPart(j).getDisposition());	//본문이미지
							//attachment 면 첨부파일(getFileName()으로 알수있다.)
							//MimeUtillity.decodeText()로 디코딩 가능
							
							if(contents.getBodyPart(j).getDisposition()=="attachment" || contents.getBodyPart(j).getDisposition()=="Attachment"){
								is= contents.getBodyPart(j).getInputStream();
								byte[] buffer = new byte[1024];
								is.read(buffer);
						
								content +=new String(buffer);
							} else {
								content = (String) message[i].getContent();
							}
							
						}
				}
				else {
					System.out.println("error - 에러발생");
				}
				System.out.println("-----------------------------------");
				System.out.println("내용 : "+content);
				
				System.out.println("받은사람:"+to);
				System.out.println("내용타입: " +message[i].getContentType());
				System.out.println("----------------------------------------------------------------------");
				message[i].setFlag(Flags.Flag.FLAGGED, true);
			
			}
		} catch (MessagingException me) {
			me.printStackTrace();
			model.addAttribute("message", me.getMessage()+ "<br>: 메일 전송 실패");
		} catch (IOException ioe) {
			ioe.printStackTrace();
			model.addAttribute("message", ioe.getMessage()+ "<br>: 메일 전송 실패");
		} finally{
			folder.close(true);
			store.close();
		}
		return "/type/typeTen/readMail";
	}
	
	/**
	 * 보낸 메일 함 열기
	 * @return url
	 */
	@RequestMapping("openMailPassWrite.do")
	public String openMailPassWrite(){
		return "/type/typeTen/passWriteMail";
	}
	
	/**
	 * 주소록 폼 열기 
	 * @return url
	 */
	@RequestMapping("openMailAddressBook.do")
	public String openMailAddressBook(){
		return "/type/typeTen/addressBookMail";
	}
	
	/**
	 * 개인 보관함 폼 열기
	 * @return url
	 */
	@RequestMapping("openMailCubbyhole")
	public String openMailCubbyhole(){
		return "/type/typeTen/cubbyholeMail";
	}
	
	/**
	 * 휴지통 폼 열기
	 * @return url
	 */
	@RequestMapping("openMailRecycleBin.do")
	public String openMailRecycleBin(){
		return "/type/typeTen/recycleBinMail";
	}
}
